<template>
  <el-dialog
    v-model="dialogVisible"
    title="banner图修改"
    width="70%"
    :close-on-click-modal="false"
  >
    <el-form ref="myForm" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :md="12" :lg="8">
          <el-form-item label="栏目" prop="t_cat_fk">
            <cat-list v-model="formData.t_cat_fk" :empty="false" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片" prop="file_path">
            <section class="resource-box">
              <el-upload
                class="upload"
                accept="image/*"
                drag
                :show-file-list="false"
                :before-upload="handleBeforeUpload"
                :http-request="handleHttpRequest"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽文件或 <em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">请上传小于2MB的图片</div>
                  <el-progress :percentage="progressNum" />
                </template>
              </el-upload>
              <img
                class="resource-img"
                :src="formData.image_path"
                v-if="formData.image_path"
              />
            </section>
            <el-input
              v-model="formData.image_path"
              placeholder="请上传图片或者填入路径"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button @click="handleClose(false)">取消</el-button>
        <el-button type="primary" @click="handleUpdate(myForm)">修改</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { UploadFilled } from "@element-plus/icons-vue";
import { defineProps, defineEmits, reactive, watch, ref } from "vue";
import { ajax } from "@/util/request";
import type {
  FormInstance,
  FormRules,
  UploadRequestOptions,
  UploadRawFile,
} from "element-plus";
import CatList from "../public/cat-list";
import setupUpload from "@/util/upload";

let updated = false;

let formData = reactive({
  password: "",
});
let myForm = ref<FormInstance>();

let { progressNum, asyncRequest } = setupUpload(formData);

let rules = reactive<FormRules>({
  t_cat_fk: [{ required: true, message: "请选择栏目", trigger: "change" }],
  image_path: [
    { required: true, message: "请上传图片", trigger: "blur" },
    { validator: checkPath, trigger: "blur" },
  ],
});

let props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  row: {
    type: Object,
  },
});

watch(
  () => props.row,
  (newVal) => {
    updated = false;
    Object.assign(formData, newVal);
    progressNum = 0;
    console.log("formData = ", formData);
  },
  {
    immediate: true,
  }
);

function handleHttpRequest(options: UploadRequestOptions): void {
  asyncRequest(options).then((res) => {
    formData.image_path = res.file_path;
  });
}

let emit = defineEmits();

/**
 * 关闭当前模态框
 */
function handleClose() {
  emit("close", updated);
}

function handleUpdate(myForm: FormInstance) {
  myForm.validate((valid) => {
    if (!valid) {
      return;
    }
    let obj = { ...formData };

    ajax("/banner/insert", obj).then((res) => {
      // 增加成功
      if (res.data.status > 0) {
        alert({ type: "success", message: "增加成功" });
        myForm.resetFields();
        updated = true;
        handleClose();
      }
    });
  });
}

function handleBeforeUpload(rawFile: UploadRawFile) {
  // 只能小于500kb的文件
  if (rawFile.size > 1024 * 1024 * 2) {
    alert({ type: "error", message: "请上传小于2MB的文件" });
    return false;
  }
  // 只能上传图片：
  if (!rawFile.type.startsWith("image/")) {
    alert({ type: "error", message: "请上传图片" });
    return false;
  }
}

// 校验图片路径是否合法
async function checkPath(rule: any, value: string, callback: any) {
  // 异步访问
  function getPromise() {
    return new Promise(function (resolve, reject) {
      var ImgObj = new Image();
      ImgObj.src = value;
      ImgObj.onload = function (res) {
        resolve(res);
      };
      ImgObj.onerror = function (err) {
        reject(err);
      };
    });
  }
  try {
    await getPromise();
    callback();
  } catch {
    callback(new Error("图片路径不合法"));
  }
}
</script>

<style scoped>
.resource-box {
  display: flex;
  flex-wrap: wrap;
}

.upload {
  width: 300px;
}

.resource-img {
  width: auto;
  height: 236px;
  box-sizing: border-box;
  margin-left: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  text-align: center;
}
</style>